package co.za.itweb.itwebpro;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.ConfigurationBuilder;

public class FavoriteNews extends Activity {

	LinearLayout linear;
	private SimpleGestureFilter detector;
	int positionX;
	String itemID;
	SeekBar seek;
	int start = 0;
	int end = 10;
	int start_pos = 0;
	int start_position = 0;
	int baseTextSize;
	private co.za.itweb.itwebpro.QuickAction mQuickAction;
	private static final int FAVORITE = 1;
	private static final int TWITTER = 2;
	private static final int EMAIL = 3;
	ActionItem addToFavs;
	int feed;
	private String title;
	private String image;
	private String author;
	private String date;
	private String link;
	private String text;
	
	private SeekBar sik;
	private TextView titleview;
	private TextView TextAuthor;
	private TextView Story;
	private TextView DateText;

	public String accessToken;
	public String accessTokenSecret;
	TweetTask tt;
	ResumeTask rt;
	UpdateTask ut;
	public Twitter mTwitter;
	public boolean haveConnectedWifi;
	public boolean haveConnectedMobile;
	String oauthVerifier;
	public int TWITTER_AUTH = 55;
	public RequestToken mRequestToken;
	private boolean tweeted = false;
	public String disqus;
	private String density2;
	private int width;
	private String mainfolder;
	private int bannerHolderWidth2;
	private WebView myWebView;
	int id;
	private String feedid;
	private WebView banner;
	private ImageButton fontbut;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.singlefavorite_item);

		Bundle extras = getIntent().getExtras();
		id = extras.getInt("id");
		feedid = extras.getString("feedid");
		title = extras.getString("title");
		image = extras.getString("image");
		author = extras.getString("author");
		date = extras.getString("date");
		link = extras.getString("link");
		disqus = extras.getString("disqus");
		text = extras.getString("text");

		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);

		width = metrics.widthPixels;
		if (width <= 250) {
			mainfolder = "240";

		} else if (width > 250 && width <= 320) {
			mainfolder = "320";

		} else if (width > 320 && width <= 480) {
			mainfolder = "480";

		} else if (width > 480 && width <= 720) {
			mainfolder = "720";
		} else if (width > 720 && width <= 800) {
			mainfolder = "800";
		} else if (width > 800 && width <= 1280) {
			mainfolder = "1280";
		} else {
			mainfolder = "1280";
		}
		
		
		Button back = (Button) findViewById(R.id.back);
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

		Button share = (Button) findViewById(R.id.share);
		share.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mQuickAction.show(v);
				mQuickAction.setAnimStyle(QuickAction.ANIM_GROW_FROM_RIGHT);
			}
		});

		ActionItem addToFavs = new ActionItem(FAVORITE, "Add to favorites",
				getResources().getDrawable(R.drawable.star_gold));
		ActionItem tweet = new ActionItem(TWITTER, "Tweet", getResources()
				.getDrawable(R.drawable.twitter));
		ActionItem email = new ActionItem(EMAIL, "Email to friend",
				getResources().getDrawable(R.drawable.email));
		mQuickAction = new QuickAction(getApplicationContext(),
				QuickAction.VERTICAL);

		mQuickAction.addActionItem(tweet);
		mQuickAction.addActionItem(email);

		tt = new TweetTask(this);
		rt = new ResumeTask();
		ut = new UpdateTask(this);

		SharedPreferences settings = PreferenceManager
				.getDefaultSharedPreferences(FavoriteNews.this);
		accessToken = settings.getString("twitter_access_token", null);
		accessTokenSecret = settings.getString("twitter_access_token_secret",
				null);

		mQuickAction
				.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
					@Override
					public void onItemClick(QuickAction quickAction, int pos,
							int actionId) {

						if (actionId == FAVORITE) {

						} else if (actionId == TWITTER) {
							if (tweeted == false) {
								if (accessToken == null
										|| accessToken.length() < 2) {
									tt.execute();

								} else {

									ut.execute();

								}
							}

						} else if (actionId == EMAIL) {
							final Intent emailIntent = new Intent(
									android.content.Intent.ACTION_SEND);
							emailIntent.setType("plain/text");
							emailIntent.putExtra(
									android.content.Intent.EXTRA_EMAIL,
									new String[] { "" });
							emailIntent.putExtra(
									android.content.Intent.EXTRA_SUBJECT,
									"ITWeb PRO article - "
											+ titleview.getText());
							emailIntent.putExtra(
									android.content.Intent.EXTRA_TEXT, link);

							startActivity(Intent.createChooser(emailIntent,
									"Send email..."));
						} else {

						}
					}
				});

		mQuickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
			@Override
			public void onDismiss() {

			}
		});

		titleview = (TextView) findViewById(R.id.textarticle);
		titleview.setText(title);
		TextAuthor = (TextView) findViewById(R.id.author);

		Story = (TextView) findViewById(R.id.summary);
		Story.setText(text);
		DateText = (TextView) findViewById(R.id.published);
		if (author.length() > 3) {
			TextAuthor.setText("By: " + author);
		}
		if (date != null) {
			DateText.setText("Published on: " + date);
		}
		ImageView bigImageView = (ImageView) findViewById(R.id.bigimage);

		LazyLoadImage icondownloader = new LazyLoadImage(bigImageView);
		Bitmap avatar = icondownloader.getBitmapFromCache(image);

		if (avatar == null) {
			icondownloader.execute(image);

		} else {

			bigImageView.setImageBitmap(avatar);
		}
		
		
		fontbut = (ImageButton)findViewById(R.id.fontresizer);
		fontbut.setOnClickListener(new OnClickListener(){
			

			@Override
			public void onClick(View v) {
				Intent intenty = new Intent(FavoriteNews.this,
						FontDialog.class);
				intenty.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivityForResult(intenty,77);
				
			}
		});

		Story.setTextSize(News.discrete);
		
		
		
		if (disqus.equals("true")) {
			RelativeLayout linLayout = (RelativeLayout) findViewById(R.id.disquss);

			if (determineDensity() == "ldpi") {
				bannerHolderWidth2 = (int) (int) (width + (width / 3)) - 10;
			} else if (determineDensity() == "mdpi") {
				bannerHolderWidth2 = (int) (width) - 10;
			} else if (determineDensity() == "hdpi") {

				bannerHolderWidth2 = (int) (width - (width / 3)) - 10;

			} else if (determineDensity() == "xdpi") {
				bannerHolderWidth2 = (int) width + (width / 2) - 10;
			}
			RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
					width, LayoutParams.WRAP_CONTENT);

			myWebView = new WebView(FavoriteNews.this);
			linLayout.addView(myWebView, layoutParams);

			String articleTITLE = titleview.getText().toString();

			((WebView) myWebView).getSettings().setJavaScriptEnabled(true);

			int currentapiVersion = Build.VERSION.SDK_INT;
			if (currentapiVersion <= Build.VERSION_CODES.GINGERBREAD) {
				System.out.println("Verzija: " + currentapiVersion);
				((WebView) myWebView).setWebViewClient(new WebViewClient() {

				});
				((WebView) myWebView).setWebChromeClient(new WebChromeClient() {
					@Override
					public boolean onJsAlert(WebView view, String url,
							String message, final android.webkit.JsResult result) {
						Toast.makeText(getApplicationContext(), message,
								Toast.LENGTH_SHORT).show();
						result.confirm();
						return true;
					}
				});

				((WebView) myWebView)
						.loadData(
								"<html><head><meta name=\"viewport\" content=\"minimum-scale=1.0; maximum-scale=1.0; user-scalable=false; initial-scale=1.0;\"/><style>html,body,iframe{margin:0;padding:0;}</style></head><body><iframe style=\"width:"
										+ bannerHolderWidth2
										+ "px;height:600px;border:0px;margin:0px;\" src=\"http://itweb.mobi/disqus-comments.php?id="
										+ id
										+ "&url=source=android&tag=article&id="
										+ id
										+ "&title="
										+ articleTITLE
										+ "\"></iframe></body></html>",
								"text/html", null);

			} else {
				System.out.println("Verzija TREBALO BI : " + currentapiVersion);
				((WebView) myWebView).setWebViewClient(new WebViewClient() {

				});
				((WebView) myWebView).setWebChromeClient(new WebChromeClient() {
					@Override
					public boolean onJsAlert(WebView view, String url,
							String message, final android.webkit.JsResult result) {
						Toast.makeText(getApplicationContext(), message,
								Toast.LENGTH_SHORT).show();
						result.confirm();
						return true;
					}
				});

				((WebView) myWebView)
						.loadUrl("http://itweb.mobi/disqus-comments.php?id="
								+ id
								+ "&url=source=android&tag=article&id="
								+ id + "&title=" + articleTITLE);

			}

		}
		

		RelativeLayout lin = (RelativeLayout) findViewById(R.id.webbanner);

		if (width >= 728) {
			RelativeLayout.LayoutParams layout2 = new RelativeLayout.LayoutParams(
					728, RelativeLayout.LayoutParams.WRAP_CONTENT);
			banner = new WebView(FavoriteNews.this);
			lin.addView(banner, layout2);
		} else {
			RelativeLayout.LayoutParams layout = new RelativeLayout.LayoutParams(
					width, RelativeLayout.LayoutParams.WRAP_CONTENT);
			banner = new WebView(FavoriteNews.this);
			lin.addView(banner, layout);
		}

		banner.getSettings().setJavaScriptEnabled(true);

		((WebView) banner).setWebChromeClient(new WebChromeClient() {

		});

		banner.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				if (url != null && url.startsWith("http://")) {
					view.getContext().startActivity(
							new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
					return true;
				} else {
					return false;
				}

			}

		});

		
		banner.loadUrl("http://itweb.mobi/__bottombar/index.php?app=itwebpro&device=android&width="
				+ mainfolder
				+ "&height=50&density="
				+ determineDensity()
				+ "&section=" + feedid);

		
		
		
		

	}
	
	public String determineDensity() {
		switch (getResources().getDisplayMetrics().densityDpi) {
		case DisplayMetrics.DENSITY_LOW:
			density2 = "ldpi";

			break;
		case DisplayMetrics.DENSITY_MEDIUM:
			density2 = "mdpi";

			break;
		case DisplayMetrics.DENSITY_HIGH:
			density2 = "hdpi";

			break;
		case DisplayMetrics.DENSITY_XHIGH:
			density2 = "xdpi";
			break;
		}
		return density2;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);

		if (requestCode == TWITTER_AUTH) {

			if (resultCode == Activity.RESULT_OK) {

				oauthVerifier = (String) data.getExtras().get("oauth_verifier");
				if (oauthVerifier != null) {
					rt.execute();
				} else {
					// tweetB.setBackgroundResource(R.drawable.twitter_visited);
					tweeted = true;
					Toast.makeText(this,
							"There has been a mistake processing your tweet !",
							Toast.LENGTH_SHORT).show();
					if (tt.getStatus() == AsyncTask.Status.RUNNING) {
						tt.dialog.dismiss();
						tt.cancel(true);

					}

					if (rt.getStatus() == AsyncTask.Status.RUNNING) {
						rt.dialog.dismiss();
						rt.cancel(true);

					}
					if (ut.getStatus() == AsyncTask.Status.RUNNING) {
						ut.dialog.dismiss();
						ut.cancel(true);
					}
				}
			} else {
				tweeted = true;
				Toast.makeText(this,
						"There has been a mistake processing your tweet !",
						Toast.LENGTH_SHORT).show();
				if (tt.getStatus() == AsyncTask.Status.RUNNING) {
					tt.dialog.dismiss();
					tt.cancel(true);

				}

				if (rt.getStatus() == AsyncTask.Status.RUNNING) {
					rt.dialog.dismiss();
					rt.cancel(true);

				}
				if (ut.getStatus() == AsyncTask.Status.RUNNING) {
					ut.dialog.dismiss();
					ut.cancel(true);
				}

			}

		}
		
		if (requestCode == 77) {

			if (resultCode == 1) {
				Story.setTextSize(News.discrete);
			}
			if (resultCode == 0) {
				
			}
			
		}
	}

	// ///////////////////////////TWITTER/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	private boolean haveNetworkConnection() {
		haveConnectedWifi = false;
		haveConnectedMobile = false;

		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo[] netInfo = cm.getAllNetworkInfo();
		for (NetworkInfo ni : netInfo) {
			if (ni.getTypeName().equalsIgnoreCase("WIFI"))
				if (ni.isConnected())
					haveConnectedWifi = true;
			if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
				if (ni.isConnected())
					haveConnectedMobile = true;
		}
		return haveConnectedWifi || haveConnectedMobile;
	}

	private class TweetTask extends AsyncTask<Void, Void, Integer> {
		private FavoriteNews activity;
		ProgressDialog dialog;

		public TweetTask(FavoriteNews activity) {
			this.activity = activity;

		}

		protected void onPreExecute() {
			dialog = new ProgressDialog(activity);
			dialog.setMessage("Tweeting...");

			dialog.setCancelable(true);
			dialog.setMax(100);
			dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
				public void onCancel(DialogInterface dialog) {
					tt.cancel(true);
					FavoriteNews.this.finish();
				}
			});
			this.dialog.show();

		}

		@Override
		protected Integer doInBackground(Void... params) {

			SharedPreferences settings = PreferenceManager
					.getDefaultSharedPreferences(getApplicationContext());

			accessToken = settings.getString("twitter_access_token", null);
			accessTokenSecret = settings.getString(
					"twitter_access_token_secret", null);
			haveNetworkConnection();
			if ((haveConnectedWifi) || (haveConnectedMobile)) {

				if ((accessToken == null) || (accessTokenSecret == null)) {
					mTwitter = new TwitterFactory().getInstance();
					mRequestToken = null;
					mTwitter.setOAuthConsumer(Constants.CONSUMER_KEY,
							Constants.CONSUMER_SECRET);
					String callbackURL = getResources().getString(
							R.string.twitter_callback);
					try {
						mRequestToken = mTwitter
								.getOAuthRequestToken(callbackURL);

						return (Integer) 1;
					} catch (TwitterException e) {
						e.printStackTrace();
					}

				} else {

					return 0;
				}
			} else {

				return 0;
			}

			return 0;
		}

		@Override
		protected void onPostExecute(Integer result) {
			if (dialog.isShowing()) {
				dialog.dismiss();
				if (result == 1) {
					setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
					startIt();
				}
			}

		}
	}

	public void startIt() {
		Intent i = new Intent(FavoriteNews.this, TwitterWebviewActivity.class);
		i.putExtra("URL", mRequestToken.getAuthenticationURL());
		startActivityForResult(i, TWITTER_AUTH);

	}

	private class ResumeTask extends AsyncTask<String, Void, Integer> {
		private String oauth;
		ProgressDialog dialog;

		protected void onPreExecute() {
			oauth = oauthVerifier;
			dialog = new ProgressDialog(FavoriteNews.this);
			dialog.setMessage("Tweeting...");

			dialog.setCancelable(true);
			dialog.setMax(100);
			dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
				public void onCancel(DialogInterface dialog) {
					rt.cancel(true);
					FavoriteNews.this.finish();
				}
			});
			this.dialog.show();

		}

		public ResumeTask() {

		}

		@Override
		protected Integer doInBackground(String... params) {
			AccessToken at = null;

			try {
				// Pair up our request with the response
				at = mTwitter.getOAuthAccessToken(oauth);
				String theToken = at.getToken();
				// Toast.makeText(this, theToken, 10000).show();
				String theTokenSecret = at.getTokenSecret();
				// Toast.makeText(this, theTokenSecret, 10000).show();
				SharedPreferences settings = PreferenceManager
						.getDefaultSharedPreferences(getApplicationContext());
				settings = PreferenceManager
						.getDefaultSharedPreferences(getApplicationContext());
				SharedPreferences.Editor editor = settings.edit();
				editor.putString("twitter_access_token", theToken);
				editor.putString("twitter_access_token_secret", theTokenSecret);
				editor.commit();
				return (Integer) 1;

				// updateStatus();
			} catch (TwitterException e) {
				e.printStackTrace();
				return 0;
			}
		}

		@Override
		protected void onProgressUpdate(Void... values) {

		}

		@Override
		protected void onPostExecute(Integer result) {
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
			if (result == 1) {
				resumeIt();
			}

		}

	}

	public void resumeIt() {
		ut.execute();

	}

	private class UpdateTask extends AsyncTask<Void, Void, Integer> {

		ProgressDialog dialog;
		private FavoriteNews activity;

		protected void onPreExecute() {
			dialog = new ProgressDialog(activity);
			dialog.setMessage("Tweeting...");

			dialog.setCancelable(true);
			dialog.setMax(100);
			dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
				public void onCancel(DialogInterface dialog) {
					ut.cancel(true);
					FavoriteNews.this.finish();
				}
			});
			this.dialog.show();

		}

		public UpdateTask(FavoriteNews activity) {
			this.activity = activity;

		}

		@Override
		protected Integer doInBackground(Void... params) {

			SharedPreferences settings = PreferenceManager
					.getDefaultSharedPreferences(getApplicationContext());
			accessToken = settings.getString("twitter_access_token", null);
			accessTokenSecret = settings.getString(
					"twitter_access_token_secret", null);

			haveNetworkConnection();
			if ((haveConnectedWifi) || (haveConnectedMobile)) {
				ConfigurationBuilder builder = new ConfigurationBuilder();
				builder.setOAuthConsumerKey(Constants.CONSUMER_KEY);
				builder.setOAuthConsumerSecret(Constants.CONSUMER_SECRET);
				builder.setOAuthAccessToken(accessToken);
				builder.setOAuthAccessTokenSecret(accessTokenSecret);
				twitter4j.conf.Configuration conf2 = builder.build();
				Twitter t = new TwitterFactory(conf2).getInstance();

				try {

					t.updateStatus(titleview.getText().toString() + " "
							+ News.tinyurl);

					//
					return (Integer) 1;
				} catch (TwitterException e) {
					e.printStackTrace();
					return 0;

				}
			} else {

				return 0;
			}
		}

		@Override
		protected void onProgressUpdate(Void... values) {

		}

		@Override
		protected void onPostExecute(Integer result) {
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
			updateIt(result);

		}
	}

	public void updateIt(Integer result) {

		if (result == 1) {
			tweeted = true;
			Toast.makeText(this, "Tweet successfully posted",
					Toast.LENGTH_SHORT).show();

		} else {
			tweeted = true;
			Toast.makeText(
					this,
					"There has been a mistake...have you already tweeted on this topic?",
					Toast.LENGTH_SHORT).show();
		}

	}

}
